package com.wenhai.spring.dependency.lookup;

import com.wenhai.spring.dependency.annotation.Super;
import com.wenhai.spring.dependency.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class DependencyLookupDemo {
    public static void main(String[] args) throws InterruptedException {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/dependency-lookup-context.xml");
        lookupCollectionByAnnotationType(beanFactory);
        lookupCollectionByType(beanFactory);
        lookupByType(beanFactory);
//        lookupInRealTime(beanFactory);
//        lookupInLazyTime(beanFactory);
    }

    private static void lookupCollectionByAnnotationType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            Map<String, User> userMap = (Map) ((ListableBeanFactory) beanFactory).getBeansWithAnnotation(Super.class);
            System.out.println("通过 Super 注解查找集合对象："+userMap);
        }
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            Map<String, User> userMap = ((ListableBeanFactory) beanFactory).getBeansOfType(User.class);
            System.out.println(userMap);
        }
    }

    private static void lookupByType(BeanFactory beanFactory) {
        System.out.println("通过类型查找 " + beanFactory.getBean(User.class));
    }

    private static void lookupInLazyTime(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory = (ObjectFactory<User>)beanFactory.getBean("objectFactory");
        System.out.println("延迟查找 " + objectFactory.getObject());
    }


    private static void lookupInRealTime(BeanFactory beanFactory) throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        System.out.println("实时查找 " + beanFactory.getBean("user"));
    }
}
